import Taro from "@tarojs/taro";
import {http} from './http'
import {PlatformSet, SubscriptionType} from './server.interface'
import {
  BASE_URL,
  GET_APP_MP,
  PAY_MP_LOGIN,
  PLATFORM_SET,
  RESOURCE_URL,
  TARO_ENV,
  GET_INDEX_NAVIGATION,
  DEFAULT_SELLER_LOGIN, GET_INIT_CODE
} from '../constants/api'
import {user} from "./user.service";
import {GetRequest, getTokenFromCookies} from "./tools";
import {lxH5Wx} from "./lx.h5.service";
import {fetchSupport} from "./getCommonData";

class PlatformSetting {
  info: PlatformSet = {
    poster_show_phone: 0,
    is_show_rank: 1,
    isShowServicePhone: 0,
    platformServicePhone: '',
    platformName: '',
    platformSellerType: 0,
    platformLogo: '',
    sellerRegType: 0,
    payVersion: 0,
    hideWc: 1,
    checkStyleMini: 0,
    isHideNavigation: 1,
    indexNavigation: false,
    authorizationType: 0,
    openSaleMessageSubscribe: 0,
    saleMessageTemplateId: [],
    movieDay: 3,
    codeWay: 0,
    status_mp: 0,
    isSellerPermanentLock: 0,
    payMethod: 0
  }
  subscription: SubscriptionType = {
    title: '',
    type: 0,
    sub_title: '',
    img: '',
    show_place: ''
  }
  indexNavigation: false
  support: any
  isLoaded = false
  upTime = 0
  scene = 0
  customTitleBar: { statusBar: number; top: number } | false = false

  async getSetting() {
    const thisTime = new Date().getTime()
    if (this.isLoaded && (thisTime - this.upTime) < 300000) {
      return this.info
    }
    const ret: any = await this.getServerSet()
    if (ret) {
      this.info = ret
      this.upTime = new Date().getTime()
      this.isLoaded = true
      return this.info
    } else {
      return false
    }
  }

  async getPlatFormSet(){
    const ret: any = await http.get<PlatformSet>(PLATFORM_SET, {})
    if (ret) {
      this.info = ret
      return ret
    } else {
      return false
    }
  }

  async getServerSet() {
    const ret: any = await http.get<PlatformSet>(PLATFORM_SET, {})
    if (ret) {
      this.info = ret
      if ("status_mp" in ret && ret.status_mp) {
        http.get<SubscriptionType>(GET_APP_MP, {}).then((res: any) => {
          if (res) {
            this.subscription = res
          }
        })
      }
      return ret
    } else {
      return false
    }
  }

  async getSupport() {
    if (TARO_ENV === 'weapp' || TARO_ENV === 'tt' || TARO_ENV === 'kwai') {
      this.support = await fetchSupport()
    } else {
      const query: any = Taro.getCurrentInstance().router.params || {}
      const pathname = document.location.pathname
      const { href, hostname, origin } = window.location
      if (query.defaultSellerLogin && query.defaultSellerLogin === '1') {
        return window.location.replace('http://' + hostname + '/' + DEFAULT_SELLER_LOGIN + '?referer=' + encodeURIComponent(href.replace(/defaultSellerLogin/g, 'defaultSellerLoginDone')) + "&t=" + new Date().getTime() + '&pkey=' + query.pkey)
      }
      const u = Taro.getStorageSync('user') || ''
      const token = getTokenFromCookies(document.cookie, u)
      if (token && u && u.pkey) {
        this.support = await fetchSupport()
      } else {
        if (process.env.P_ENV === 'lx') {
          if (!lxH5Wx.isLogin) {
            const initCode = await http.carGet(GET_INIT_CODE)
            lxH5Wx.getRequestCode(initCode, true)
          }
          return false
        }
        let _referer = encodeURIComponent(href);
        if (pathname != '/pay/success' && !query.pkeys && pathname != "/pay/index" && TARO_ENV === 'h5') {
          const api = DEFAULT_SELLER_LOGIN
          let flag = false
          if (query.defaultSellerLogin && query.defaultSellerLogin === '1') {
            _referer = encodeURIComponent(decodeURIComponent(_referer).replace(/defaultSellerLogin/g, 'defaultSellerLoginDone'))
            flag = true
          }
          let url = origin + api + '?referer=' + _referer + "&t=" + new Date().getTime()
          if (flag) {
            url += '&pkey=' + (query.pkey || '')
          }
          if (!flag) {
            if ((!u || !u.pkey || u.pkey === 'null') && !u.pkeys) {
              window.location.replace(origin + '/msvc-shop/v1/mp/user/pkey?referer=' + _referer)
              return false
            }
          } else {
            window.location.replace(url)
          }
          return
        }
      }
    }
  }

  async getIndexNavigation() {
    let pathname
    const params = {style: 0}
    if (TARO_ENV === 'h5') {
      pathname = window.location.pathname
    } else {
      const pages = Taro.getCurrentPages();
      pathname = pages[pages.length - 1].route
    }
    if (pathname === '/' || pathname === '/pages/index/big' || pathname === 'pages/index/big') {
      params.style = 1
    }
    const ret = await http.get(GET_INDEX_NAVIGATION, params)
    if (ret && ret.indexNavigation) {
      return ret.indexNavigation
    }
    return false
  }

}

export const platform = new PlatformSetting()
